<?php

/**
 * 这个class用于机构的各种会员卡管理，会员卡的类型可能包括：会员（资格卡），
 * 会员积分卡等等。
 * *****************
 * 如何使用这个class:
 * 1)一般来说，这个cooker对应于一个Event,可以定义一个会员卡的event，然后使用这个cooker
 * 定义一个event的方式大概包括的步骤是：
 * a)在app的run函数里面添加功能类型，如：
 * class BWeCafe extends BApp {
  public function run($data = NULL) {
  parent::run($data);
  $cooker = new BAEventCooker();
  $cooker->addEventType('weBill', '买单功能');
  $cooker->addEventType('memberPoint', '会员积分');
  $cooker->addEventType('memberCard', '会员卡');
  $cooker->addEventType('membership', '会员资格');
 * b)在admin里面添加event来添加会员卡功能
 * ***********************************************
 * 基本功能：
 * 1）系统管理员添加会员卡类型，类型可能包括：会员资格卡，会员积分卡
 * 相关的function包括：
 * onShowCardTypeList
 * onShowAddCardType
 * onAddCardType
 * getCardTypeList
 * getCardType($cardData):通过id,名字等获得类型
 * getCurrentCardType():获取当前的类型，可以通过这个函数来避免cardTypeId的反复传递，
 * 在任何一个点都可以获得当前的cardType
 * addCardType,deleteCardType:这是具体实现添加删除的地方，应该在这里进行数据库操作
 * 数据库设计：
 * 所有卡类型放在一个表里面，$cardTable = new BASpaceSheet('memberCardType',$event);
 * 2)系统管理员可以设置会员卡的一些特别属性，比如模板，申请规则等(申请规则的说明参照BAVoucherCooker
 * 里面的说明，和里面的设计完全一致）
 * 相关的函数包括：
 * getCardTypeTemplateData:获取卡类型的模板，模板通常就是一个目录下的一组view，这个函数
 * 将返回相当于eventType的目录结构，比如，在memberCard功能下面，模板放在..\memberCard\template\classic
 * 下面,那么模板选择template.classic，就可以调用相应目录下面的view来显示
 * 申请规则是一组permit，通过BAPermitCooker来完成，相关函数以及使用方法见BAVoucherCooker里面的说明
 * 以及BAPermitCooker里面的说明
 * 3）客户端显示会员卡列表，会员卡领取列表和会员卡申请列表，客户可以领取会员卡
 * 或者申请会员卡，创建的会员卡会显示在客户的会员卡列表里面
 * 客户可以通过微信菜单进入会员卡主页，主页将显示会员卡领取列表（如果有），申请列表（如果有）以及
 * 客户会员卡列表。会员卡列表可以考虑通过一个滑动列表的方式方式来显示
 * 相关的函数包括：
 * onShowUserCardAddableList:显示会员卡的领取列表（不需要批准），通过这个列表，客户可以领取会员卡
 * ，即调用addCard来为用户添加会员卡
 * onShowUserCardApprovableList：显示会员卡的申请列表（需要批准）
 * onShowUserCardList：显示客户已有的会员卡列表，可以考虑用左右滑动列表的方式显示
 * getUserCardAddableList：这个函数需要首先判断客户是否满足添加卡的申请规则，如果满足而且未申请
 * 就列在这个列表里面
 * getUserCardApprovableList：产生相应审批的会员卡列表
 * getUserCardList：用户已经申请的会员卡列表（未过期）
 * getMemberCard($cardData)
 * getCurrentMemberCard():可以用来避免反复传递cardId
 * onShowAddCard:用户领取卡的时候，需要调用这个函数显示领取卡页面或者直接添加卡
 * onAddCard：执行添加卡的操作
 * addCard：数据库操作的地方
 * deleteCard：删除卡的数据库操作
 * 数据库设计：
 * 创建的卡都放在卡列表，卡列表的设计是： $cardTable = new BASpaceSheet('memberCard',$cardType)
 * 保存的时候，卡的状态可能包括几种：如：applying,approved等
 * 4）积分卡上面，将会显示客户的积分信息，并提供链接，让客户可以访问积分记录
 * 在添加积分卡类型时候，系统管理员需要指定对应的积分类型，积分类型需要通过先添加
 * 积分功能，并添加积分类型后才能获得，在积分卡里面，填入对应的积分类型名称就可以
 * 指定对应的积分类型
 * 当客户添加了积分卡以后，可以通过用户的手机号以及绑定的积分类型，查找到用户的积分帐号
 * 并通过积分帐号获取客户的积分以及访问客户的积分记录
 * 相关的函数包括：
 * $account=BAMemberPointCooker->getUserAccount($memberPointType,$userInfo) -- 调用
 * $account->getItem('point')->getValue来获取积分
 * $memberPointCooker->onShowMemberPointHistory() --调用来显示积分记录
 * 5）机构管理员可以通过用户手机号查看用户的会员卡
 * 机构管理员可以查看用户的卡列表，包括申请礼拜，积分卡列表
 * 管理员通过输入用户手机号等方式，可以获得用户的卡列表，管理员可以执行删除等操作
 * 相关的函数包括：
 * onShowCardList:显示机构的用户的卡的列表，可以设置各种显示条件
 * 
 *
 * @author jianfeng
 */
class BAMemberCardCooker extends BAEventCooker {

    const CardType_MemberPoint_Card = 'memberPointCard';
    const CardType_Membership_Card = 'membershipCard';
    const Permit_Allow_AddCard = 'allow_add_card';
    const Permit_Allow_Approve = 'allow_approve';

    /**
     * 和cardType有关的函数
     */
    public function onShowCardTypeList($control = NULL) {
        $eventHome = $this->getCurrentEventHome();
        $view = 'memberCardType_list_' . $eventHome;
        if ($control != NULL) {
            $control->addRenderView('showTypeList', $view, array('memberCardTypeList' => $this->getCardTypeList('arrayList')));
        } else {
            $this->updateControl->addRenderView('showTypeList', $view, array('memberCardTypeList' => $this->getCardTypeList('arrayList')));
        }
    }

    public function onShowAddCardType() {
        $this->updateControl->addRenderView('memberCardType_add');
    }

    public function onShowAddCardTypeInfo($preCardType = NULL, $typeId = NULL) {

        if ($preCardType == NULL) {
            $preCardTypeMediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'choose_cardType');
            if ($preCardTypeMediaList != NULL) {
                $preCardTypeMedia = $preCardTypeMediaList['preCardType'];
                $preCardType = $preCardTypeMedia->content;
            }
        }

        //first check memberPointType if add memberPointCard
        if ($preCardType == self::CardType_MemberPoint_Card) {
            $memberPointCooker = new BAMemberPointCooker();
            $memberPointTypeList = $memberPointCooker->getMemberPointTypeList();

            if ($memberPointTypeList == NULL || empty($memberPointTypeList)) {
                $this->updateControl->addRenderView('memberPointType_not_exist_error');
                return;
            }
        }

        if ($typeId == NULL) {
            $typeId = $this->activeLink->getLinkVariable('memberCardTypeId');
        }
        //$type = $this->getCurrentCardType();

        $model = new BDynamicFormModel();
        $typeNameField = 'media_name_add_memberCardType';
        $typeAliasField = 'media_alias_add_memberCardType';
        $templateField = 'media_template_add_memberCardType';
        $memberPointTypeField = 'media_memberPointType_add_memberCardType';
        $moneyField = 'media_money_add_memberCardType';

        $model->addField($typeNameField);
        $model->addField($typeAliasField);
        $model->addField($templateField);
        $model->addField($memberPointTypeField);
        $model->addField($moneyField);

        //$typeTable = new BASpaceSheet('memberCardType', $this->getCurrentEvent());
        $type = NULL;
        if (is_numeric($typeId) && $typeId > 0) {

            $type = $this->getCardType($typeId);

            if ($preCardType == NULL && $type != NULL) {
                $preCardType = $this->getPreCardTypeFromCardType($type);
            }

            $typeAttributeTable = new BAAttributeSheet($type);

            $typeList = $typeAttributeTable->getList(array('itemData' => array('memberCardTypeId' => $typeId)));

            //将已经存在的数据放进MODEL里面
            if ($typeList instanceof BTreeList) {
                if ($typeList->getItem('name') != NULL)
                    $model->$typeNameField = $typeList->getItem('name')->getValue();
                if ($typeList->getItem('alias') != NULL)
                    $model->$typeAliasField = $typeList->getItem('alias')->getValue();
                if ($typeList->getItem('template') != NULL)
                    $model->$templateField = $typeList->getItem('template')->getValue();
            }

            if ($typeList->getItem('memberPointType') != NULL) {
                $model->$memberPointTypeField = $typeList->getItem('memberPointType')->getValue();
                $preCardType = self::CardType_MemberPoint_Card;
            }


            if ($typeList->getItem('money') != NULL) {
                $model->$moneyField = $typeList->getItem('money')->getValue();
                $preCardType = self::CardType_Voucher_Card;
            }
        }

        $viewData = array(
            'model' => $model,
            'typeNameField' => $typeNameField,
            'typeAliasField' => $typeAliasField,
            'templateField' => $templateField,
            'memberCardTypeId' => $typeId,
            'memberPointTypeField' => $memberPointTypeField,
            'moneyField' => $moneyField,
            'memberCardType' => $type,
            'preCardType' => $preCardType
        );

        $this->updateControl->addRenderView('addMemberCardType', 'memberCardType_add_1', $viewData);
    }

    /**
     * this function use to add card type.
     * usually each space can add several type of card
     * use this function to catch data from input and create card type
     */
    public function onAddCardType() {
        //$typeId = $this->activeLink->getLinkVariable('memberCardTypeId');
        $preCardType = $this->activeLink->getLinkVariable('preCardType');
        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'add_memberCardType');

        $itemData = array();
        foreach ($mediaList as $media) {
            $name = $media->name;
            $value = $media->content;
            if ($value != NULL || $value != '') {
                $itemData[$name] = $value;
            }
        }

        //adjust type name
        if (is_string($preCardType) && $preCardType != NULL) {
            $itemData['name'] = $preCardType . '.' . $itemData['name'];
        }

        $type = $this->addCardType($itemData['name'], $itemData['alias'], $itemData);

        //add permit for type
        $permitData['cardTypeId'] = $type->getId();
        //默认是机构客户都可以申请卡
        $permitData['roleId'] = BARoleCooker::getSpaceCustomerRole()->getId();
        //默认情况下，不需要审批，自动添加卡
        $permitData['permit'] = self::Permit_Allow_AddCard;

        $permitCooker = new BAPermitCooker();

        $this->addCardTypePermit($permitData, $type);

        $this->onShowAddCardTypeInfo($preCardType, $type->getId());
    }

    public function onDelCardType() {
        $typeId = $this->activeLink->getLinkVariable('memberCardTypeId');
        if ($typeId != NULL) {
            //$itemData = array();
            //check if exist type
            //$itemData['memberCardTypeId'] = $typeId;
            $typeTable = new BASpaceSheet('memberCardType');
            $typeTable->deleteList($typeId);
        }
        $this->onShowCardTypeList();
    }

    public function addCardType($name, $alias = null, $data = NULL) {

        $memberCardTypeRoot = $this->getCardTypeRoot();

        if ($alias == NULL) {
            $alias = $name;
        }
        $type = $memberCardTypeRoot->addChild(array('name' => $name, 'value' => $alias));
        if ($type != NULL) {
            $itemData = array();
            //check if exist type
            $itemData['memberCardTypeId'] = $type->getId();
            $typeAttributeTable = new BAAttributeSheet($type);
            $list = $typeAttributeTable->getList(array('itemData' => $itemData));

            if ($list == NULL) {
                $list = $typeAttributeTable->getNewList();
            }

            $itemData['name'] = $name;
            $itemData['alias'] = $alias;
            if (is_array($data)) {
                $itemData+=$data;
            }

            //check if data changed, if not, no need to save
            $list2 = $typeAttributeTable->getList(array('itemData' => $itemData));
            if ($list2 == NULL)
                $list->addItems($itemData);

            return $type;
        }
        return FALSE;
    }

    public static function getPreCardTypeList($data = NULL) {

        $typeList = array();
        $typeList[self::CardType_MemberPoint_Card] = '积分卡';
        $typeList[self::CardType_Membership_Card] = '会员卡';

        return $typeList;
    }

    protected function getCardTypeRoot() {
        $category = new BACategory();
        $categoryRoot = $category->getRootNode();
        $memberCardTypeRoot = $categoryRoot->getChild('memberCardType');
        if ($memberCardTypeRoot == NULL) {
            $memberCardTypeRoot = $categoryRoot->addChild('memberCardType');
        }
        return $memberCardTypeRoot;
    }

    /**
     * 
     * @param string formate, can be aliasList, nameList,objectList,arrayList
     * @param type $data
     * @return type
     */
    public function getCardTypeList($formate = 'aliasList', $preCardType = null, $data = NULL) {

        $parent = $this->getCardTypeRoot();

        if ($preCardType != NULL) {
            $parent = $parent->getChild($preCardType);
        }

        $children = $parent->getChildrenAsLeaf();

        if (strtolower($formate) == 'objectlist') {
            return $children;
        }

        $list = array();

        foreach ($children as $id => $type) {

            if (strtolower($formate) == 'arraylist') {
                $item = array();
                $item['id'] = $id;
                $item['name'] = $typeName = $type->getName();
                $item['alias'] = $type->getValue();

                $tNames = explode('_', $typeName);
                $appName = $tNames[0];
                $item['appName'] = $appName;
//                $item['permit'] = $this->getMemberCardTypePermit($id);

                $list[$id] = $item;
            }
            if (strtolower($formate) == 'namelist') {
                $list[$id] = $type->getName();
            }
            if (strtolower($formate) == 'aliaslist') {
                $list[$id] = $type->getValue();
            }
        }

        return $list;
    }

    public function getCardType($nameOrId, $data = NULL) {

        if (is_numeric($nameOrId) && $nameOrId > 0) {
            return new BACategory($nameOrId);
        }

        if (is_string($nameOrId) && $nameOrId != NULL && $nameOrId != '') {
            $memberCardTypeRoot = $this->getCardTypeRoot();
            $cardType = $memberCardTypeRoot->getChild($nameOrId);

//add memberPointCardType if not exist
            if ($nameOrId == self::CardType_MemberPoint_Card && $cardType == NULL) {
                $cardType = $memberCardTypeRoot->addChild(array('name' => $nameOrId, 'value' => '积分卡'));
            }

            return $cardType;
        }

        if ($nameOrId instanceof BACategory) {
            return $nameOrId;
        }

        return FALSE;
    }

    public function getCardTypeByCard($card) {

        $card = $this->getCard($card);

        if ($card != NULL) {
            $cardTypeItem = $card->getItem('cardTypeId');
            if ($cardTypeItem != NULL) {
                $cardTypeId = $cardTypeItem->getValue();
                return $this->getCardType($cardTypeId);
            }
        }
        return FALSE;
    }

    public function getCardTypeTemplateData($preCardType = NULL, $data = NULL) {
        return array();
    }

    public function getPreCardTypeFromCardType($cardType) {
        $cardType = $this->getCardType($cardType);

        if ($cardType instanceof BACategory) {
            $parent = $cardType->getParent();
            if ($parent != NULL) {
                return $parent->getName();
            }
        }
        return FALSE;
    }

    public function getCurrentPreCardType($data = NULL) {

        $cardType = $this->getCurrentCardType();
        if ($cardType != NULL) {
            return $this->getPreCardTypeFromCardType($cardType);
        }

        $preCardType = $this->activeLink->getLinkVariable('preCardType');

        if ($preCardType != NULL) {
//update value in context variable
            Blyn::app()->getUIManager()->getCurrentScreen()->addContextVariable('preCardType', $preCardType);
        } else {
            if ($preCardType == NULL) {
                //try to find from context variable
                $preCardType = Blyn::app()->getActiveOperation()->getContextVariable('preCardType');
            }
        }

        return $preCardType;
    }

    public function getCurrentCardType($data = NULL) {
        $memberCardTypeId = $this->activeLink->getLinkVariable('memberCardTypeId');
        if ($memberCardTypeId == NULL)
            $memberCardTypeId = $this->activeLink->getLinkVariable('cardTypeId');

        if (is_numeric($memberCardTypeId) && $memberCardTypeId > 0) {
//update value in context variable
            Blyn::app()->getActiveOperation()->addContextVariable('memberCardTypeId', $memberCardTypeId);
        } else {
            if ($memberCardTypeId == NULL) {
                //try to find from context variable
                $memberCardTypeId = Blyn::app()->getActiveOperation()->getContextVariable('memberCardTypeId');
            }
        }

        if (is_numeric($memberCardTypeId) && $memberCardTypeId > 0) {
            $memberCardType = new BACategory($memberCardTypeId);
            return $memberCardType;
        }
        return FALSE;
    }

    public function getCardTypeAttribute($name, $type = NULL) {

        if ($type == NULL) {
            $cardType = $this->getCurrentCardType();
        } else {
            $cardType = $this->getCardType($type);
        }

        if ($cardType != NULL) {
            $typeAttributeTable = new BAAttributeSheet($cardType);
            $attrList = $typeAttributeTable->getList();
            if ($attrList != NULL) {
                $attrItem = $attrList->getItem($name);
                if ($attrItem != NULL) {
                    return $attrItem->getValue();
                }
            }
        }
        return FALSE;
    }

    /**
     * 和会员卡相关的函数
     */
    /**
     * use to show card list, 
     */

    /**
     * 显示机构的会员卡列表，可以设置条件获取各种列表
     * 这个函数通常由管理员操作来获取机构的卡列表
     */
    public function onShowCardList() {

        $cardType = $this->getCurrentCardType();
        $cardTypeId = $cardType->getId();

        $cardView = $this->getCardList($cardType);

        $opName = Blyn::app()->getActiveOperation()->getName();

        $this->updateControl->addRenderView('memberCard_list', 'memberCard_list_' . $opName, array(
            'cardView' => $cardView,
            'cardType' => $cardType,
            'cardTypeId' => $cardTypeId));
    }

    /**
     * 添加会员卡在以下几种情况下实现：
     * 1）用户领取会员卡的时候，一般来说，领取的时候调用addCard来完成添加卡的操作
     * 2）申请会员卡批准的时候，申请批准的时候，也将调用addCard来完成添加卡的操作
     * 3）管理人员添加卡的操作，只要管理员添加卡的时候需要调用这个函数来完成添加卡的操作
     */
    public function onShowAddCard() {

        $this->updateControl->addRenderView('memberCard_add');
    }

    public function onShowAddCardInfo() {

        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'user_info');
        $userInfo = array();
        foreach ($mediaList as $media) {
            $userInfo[$media->name] = $media->content;
        }

        $userCooker = new BAUserCooker();
        $oUserInfo = $userCooker->getUserInfo($userInfo);
        /*
         * 在manager里面增加会员卡，会员卡类型由admin增加
         * 下面代码处理manager
         */
        $cardId = $this->activeLink->getLinkVariable('cardId');
        $cardTable = new BASpaceSheet('memberCard');

        $model = new BDynamicFormModel();
        $fixedCardIdField = 'media_fixedCardId_add_card';
        $mobileField = 'media_mobile_user_info';
        $genderField = 'media_gender_user_info';
        $surNameField = 'media_surName_user_info';
        $familyNameField = 'media_familyName_user_info';
        $birthField = 'media_birthField_user_info';
        $expireTimeField = 'media_expireTime_add_card';
        $descriptionField = 'media_description_add_card';

        $model->addField($fixedCardIdField);
        $model->addField($mobileField);
        $model->addField($genderField);
        $model->addField($familyNameField);
        $model->addField($surNameField);
        $model->addField($birthField);
        $model->addField($expireTimeField);
        $model->addField($descriptionField);

        //populate user info
        if ($oUserInfo->getItem('mobile') != NULL)
            $model->$mobileField = $oUserInfo->getItem('mobile')->getValue();
        if ($oUserInfo->getItem('gender') != NULL)
            $model->$genderField = $oUserInfo->getItem('gender')->getValue();
        if ($oUserInfo->getItem('familyName') != NULL)
            $model->$familyNameField = $oUserInfo->getItem('familyName')->getValue();
        if ($oUserInfo->getItem('surName') != NULL)
            $model->$surNameField = $oUserInfo->getItem('surName')->getValue();
        if ($oUserInfo->getItem('$oUserInfo') != NULL)
            $model->$surNameField = $oUserInfo->getItem('surName')->getValue();
        if ($oUserInfo->getItem('birthField') != NULL)
            $model->$birthField = $oUserInfo->getItem('birthField')->getValue();

        if ($cardId != NULL && $cardId > 0) {

            $card = $cardTable->getListById($cardId);

            //将已经存在的活动数据放进MODEL里面
            if ($card->getItem('fixedCardId') != NULL)
                $model->$fixedCardIdField = $card->getItem('fixedCardId')->getValue();
            if ($card->getItem('expireTime') != NULL)
                $model->$expireTimeField = $card->getItem('expireTime')->getValue();
            if ($card->getItem('description') != NULL)
                $model->$descriptionField = $card->getItem('description')->getValue();
        }else { //add a temporary card by userid_spaceid
            $card = $cardTable->getTempList();
        }

        $this->updateControl->addRenderView('memberCardAdd', 'memberCard_add', array(
            'model' => $model,
            'fixedCardIdField' => $fixedCardIdField,
            'genderField' => $genderField,
            'surNameField' => $surNameField,
            'familyNameField' => $familyNameField,
            'mobileField' => $mobileField,
            'birthField' => $birthField,
            'expireTimeField' => $expireTimeField,
            'descriptionField' => $descriptionField,
            'card' => $card,
            'cardId' => $cardId));
    }

    /**
     * this function display card
     */
    public function onShowCard() {

        $card = $this->getCurrentCard();
        $userCooker = new BAUserCooker();
        $mPointCooker = new BAMemberPointCooker();
        $cardInfo = array();

        if ($card != NULL) {
            $cardType = $this->getCardTypeByCard($card);
            $preCardType = $this->getPreCardTypeFromCardType($cardType);
            $userInfoId = $card->getItem('userInfoId')->getValue();
            $oUserInfo = $userCooker->getUserInfo($userInfoId);

            if ($oUserInfo != NULL) {
                $userData = $oUserInfo->getItemsInArray();
                $cardInfo+=$userData;
            }
            $cardInfo['preCardType'] = $preCardType;
            $cardInfo['cardTypeAlias'] = $cardType->getValue();

            if ($preCardType == self::CardType_MemberPoint_Card) {
                $memberPointCooker = new BAMemberPointCooker();
                //get memberPoint Type
                $memberPointTypeId = $this->getCardTypeAttribute('memberPointType', $cardType);

                $memberPointType = $memberPointCooker->getMemberPointType($memberPointTypeId);

                //get memberPointAccount
                $mpAccount = $memberPointCooker->getMemberPointAccountByUser($memberPointType);

                if ($mpAccount != NULL) {
                    $accountData = $mpAccount->getItemsInArray();
                    $cardInfo+=$accountData;
                }
            }
        }

        $this->updateControl->addRenderView('showCard', 'memberCard_display', array('cardInfo' => $cardInfo));
    }

    public function onAddCard() {

        $userMediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'user_info');

        //add user data into user table
        if ($userMediaList != NULL) {
            $userCooker = new BAUserCooker();
            $userData = array();
            foreach ($userMediaList as $media) {
                $userData[$media->name] = $media->content;
            }
            //用户数据通过link传递过来
            if (!isset($userData['userId']) && $this->activeLink->getLinkVariable('userId') != NULL) {
                $userData['userId'] = $this->activeLink->getLinkVariable('userId');
            }
            if (!isset($userData['mobile']) && $this->activeLink->getLinkVariable('mobile') != NULL) {
                $userData['mobile'] = $this->activeLink->getLinkVariable('mobile');
            }
            if (!isset($userData['email']) && $this->activeLink->getLinkVariable('email') != NULL) {
                $userData['email'] = $this->activeLink->getLinkVariable('email');
            }
            $oUserInfo = $userCooker->addUserInfo($userData);
        }

        $mcardId = $this->activeLink->getLinkVariable('memberCardId');

        $cardTable = new BASpaceSheet('memberCard', $this->getCurrentCardType());

        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'add_card');

        $itemData = array();
        if (isset($oUserInfo) && $oUserInfo != NULL) {
            $itemData['userInfoId'] = $oUserInfo->getId();
        }

        foreach ($mediaList as $media) {
            $name = $media->name;
            $value = $media->content;
            $itemData[$name] = $value;
        }

        $card = $this->addCard(NULL, $mcardId, $itemData);

        $this->onShowCardList();
    }

    public function onDelCard() {
        $cardId = $this->activeLink->getLinkVariable('cardId');
        if ($cardId != NULL) {
            $cardTable = new BASpaceSheet('memberCard', $this->getCurrentCardType());
            $cardTable->deleteList($cardId);
        }
        $this->onShowCardList();
    }

    /**
     * this function use to display member card for member
     */
    /*
      public function onShowCard() {
      $cardId = $this->activeLink->getLinkVariable('memberCardId');
      $this->updateControl->addRenderView('displayMemberCard', 'memberCardDisplay', array('memberCardId' => $cardId));
      }
     * 
     */

    public function addCard($cardType = NULL, $itemData = NULL, $memberCardId = NULL) {

        $card = NULL;

        if ($cardType == NULL) {
            $cardType = $this->getCurrentCardType();
        } else {
            $cardType = $this->getCardType($cardType);
        }

        if ($itemData == NULL) {
            $itemData = array();
        }

        if ($cardType != NULL) {

            $itemData['cardTypeId'] = $cardType->getId();

            $cardId = NULL;
            $cardTable = new BASpaceSheet('memberCard', $cardType);
            if (is_numeric($memberCardId) && $memberCardId > 0) {
                $card = $cardTable->getListById($memberCardId);
                if ($card->getName() != 'list' . $card->getId()) {
                    $card->name = 'list' . $card->getId();
                    $card->setOwner($this->getCurrentCardType());
                    $card->save();
                }
            }

            if (isset($itemData['cardId'])) {
                $cardId = $itemData['cardId'];
                $card = $cardTable->getList(array('itemData' => array('cardId' => $itemData['cardId'])));
            } else {
                $card = $cardTable->getList(array('itemData' => $itemData));
            }

            if ($card == NULL) {
                $card = $cardTable->getNewList();
            }

            if (!isset($itemData['cardId'])) {
                $itemData['cardId'] = 'card' . $card->getId();
            }

            if ($card instanceof BTreeList) {
                $card->addItems($itemData);
            }
        }

        return $card;
    }

    /**
     * 机构管理员用这个function来获取卡列表，并进行管理
     * 用户不用这个函数获取列表，用户用getUserCardList来获取用户的卡列表
     * @param type $cardType
     * @param type $operation
     * @param type $data
     * @return type
     */
    public function getCardList($cardType = null, $format = 'aliasList', $operation = NULL, $data = NULL) {

        if ($cardType == NULL) {
            $cardType = $this->getCurrentCardType();
        }

        if ($operation == NULL) {
            $operation = Blyn::app()->getActiveOperation();
        }

        $cardTable = new BASpaceSheet('memberCard', $cardType);
        $cardView = $cardTable->getView();

        return $cardView;
    }

    public function getCard($itemData = NULL, $cardType = NULL) {

        $cardTable = new BASpaceSheet('memberCard');

        if (is_numeric($itemData) && $itemData > 0) {
            return $cardTable->getListById($itemData);
        }

        if ($itemData instanceof BTreeList) {
            return $itemData;
        }

        if (is_array($itemData)) {
            $cardType = $this->getCardType($cardType);
            $cardTable = new BASpaceSheet('memberCard', $cardType);
            return $cardTable->getList(array('itemData' => $itemData));
        }

        return FALSE;
    }

    public function getCurrentCard($data = NULL) {
        $memberCardId = $this->activeLink->getLinkVariable('memberCardId');

        if (is_numeric($memberCardId) && $memberCardId > 0) {
//update value in context variable
            Blyn::app()->getActiveOperation()->addContextVariable('memberCardId', $memberCardId);
        } else {
            if ($memberCardId == NULL) {
                //try to find from context variable
                $memberCardId = Blyn::app()->getActiveOperation()->getContextVariable('memberCardId');
            }
        }

        if (is_numeric($memberCardId) && $memberCardId > 0) {
            $memberCard = $this->getCard($memberCardId);
            return $memberCard;
        }
        return FALSE;
    }

    /**
     * ********************
     * 和用户卡相关的函数
     * ********************
     */

    /**
     * 显示可以用户的会员卡领取列表和用户可以申请的卡的列表,将领取表和申请表都放在这里
     */
    public function onShowUserCardApplyList($cardTypeId = NULL, $preCardType = NULL) {

        //$cardType = $this->getCurrentCardType();
        //$preCardType = $this->getCurrentPreCardType();
        if ($cardTypeId == NULL)
            $cardTypeId = $this->activeLink->getLinkVariable('cardTypeId');
        if ($preCardType == NULL)
            $preCardType = $this->activeLink->getLinkVariable('preCardType');

        $applyList = $this->getUserMemberCardApplyList($cardTypeId, $preCardType);
        $this->updateControl->addRenderView('userMemberCardApplyList', 'memberCard_apply_list', array(
            'applyView' => $applyList
        ));
    }

    public function onShowUserAddCard() {

        $userCooker = new BAUserCooker();
        $userInfo = $userCooker->getUserInfo();

        if ($userInfo == NULL) {//means user not register so far
            $this->updateControl->addRenderView('memberCard_apply_list_header');
            $userInfoControl = new BUIThemedControl('addUserInfo');
            $this->updateControl->addChildControl($userInfoControl);
            $userCooker->showAddUserInfo($userInfoControl);
        } else {//if user register user info already
            $cardType = $this->getCurrentCardType();
            $permitId = $this->activeLink->getLinkVariable('permitId');
            $permitCooker = new BAPermitCooker();
            $permit = $permitCooker->getPermit($permitId, 'object');
            $itemData = array();
            if ($permit != NULL) {
                $itemData['permitId'] = $permit->getId();
            }
            if ($userInfo != NULL) {
                $itemData['userInfoId'] = $userInfo->getId();
            }
            //$userInfoData = $userCooker->getUserInfo(NULL, 'array');
            //$itemData = $userInfoData;
            $this->addCard($cardType, $itemData);
            $preCardType = $this->getPreCardTypeFromCardType($cardType);
            if ($preCardType == self::CardType_MemberPoint_Card) {
                $memberPointCooker = new BAMemberPointCooker();
                //get memberPoint Type
                $memberPointType = $this->getCardTypeAttribute('memberPointType', $cardType);

                $memberPointType = $memberPointCooker->getMemberPointType($memberPointType);

                //get memberPointAccount
                $account = $memberPointCooker->getMemberPointAccountByUser($memberPointType);

                if ($account == NULL) {//create it if account not exist
                    $account = $memberPointCooker->addMemberPointAccount($memberPointType, $userInfo);
                }

                if ($account != NULL) {
                    $cardInfo['memberPointAccountId'] = $account->getId();
                }
            }
            //$this->activeLink->addLinkVariable('cardTypeId', NULL);
            $this->onShowUserCardApplyList('ALL');
        }
    }

    public function onShowUserApplyCard() {
        
    }

    public function onShowCardUserBillList() {
        $BAWeBillCooker = new BAWeBillCooker();

        $BAWeBillCooker->onShowAllTypeBill();
//        $billType = $BAWeBillCooker->getCurrentBillType();
//        $billView = $BAWeBillCooker->getBillList($billType);
//
//        $this->updateControl->addRenderView('cardUserBillList', 'memberCard_bill_list', array(
//            'billView' => $billView
//        ));
    }

    public function onShowUserCardList() {

        //$cardType = $this->getCurrentCardType();
        $cardTypeId = $this->activeLink->getLinkVariable('cardTypeId');
        $preCardType = $this->activeLink->getLinkVariable('preCardType');
        $applyList = $this->getUserMemberCardApplyList($cardTypeId, $preCardType);
        $applyListCount = count($applyList); //获得可领取会员卡的个数
        $cardList = $this->getUserMemberCardList();

        $this->updateControl->addRenderView('userCardList', 'memberCard_list_member', array(
            'cardView' => $cardList,
            'applyListCount' => $applyListCount,
        ));
    }

    public function onShowUserCardHome() {
        $this->updateControl->addRenderView('memberCard_member_home');
    }

    /**
     * 在卡的可申请列表里面，用户点领取，将执行这个操作
     */
    public function onUserAddCard() {

        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'apply_memberCard');

        $itemData = array();
        foreach ($mediaList as $media) {
            $itemData[$media->name] = $media->content;
        }

        if (isset($itemData['cardTypeId'])) {
            $cardTypeId = $itemData['cardTypeId'];

            $cardType = $this->getCardType($cardTypeId);
            $memberPointCooker = new BAMemberPointCooker();

            //if it is 20元消费券,抵扣200积分并自动处理
            if (strpos($cardType->getFullName(), 'payCard.yuan20')) {
                if ($memberPointCooker->deductMemberPoint($cardType, 200) === TRUE) {
                    $card = $this->addCard($cardType);
                    $this->updateControl->addRenderView('applyCard', 'memberCard_list', array(
                        'memberCardType' => $cardType,
                        'card' => $card
                    ));
                }
            } else {//by default, send request for approvement
                $messageTable = new BAMessageSheet('applyMemberCard');
                $itemData = array();
                $itemData['send_userId'] = Blyn::app()->getCurrentUser()->getId();
                $itemData['cardTypeId'] = $cardType->getId();

                $list = $messageTable->getList(array('itemData' => $itemData));

                //if exist, return status
                if ($list instanceof BTreeList) {
                    $status = $list->getItem('status')->getValue();
                    $this->updateControl->addRenderView('applyCardStatus', 'memberCard_apply_status', array(
                        'status' => $status
                    ));
                } else {//if not exist, create a new message
                    $itemData['applyTime'] = time();
                    $itemData['send_userName'] = Blyn::app()->getCurrentUser()->getName();
                    $itemData['cardTypeFullName'] = $cardType->getFullName();
                    $itemData['cardTypeAlias'] = $cardType->getValue();
                    $itemData['status'] = 'pending';
                    $list = $messageTable->addList($itemData);
                    $this->updateControl->addRenderView('showApplyCardRequest', 'showApplyCardRequest', array(
                        'request' => $list
                    ));
                }
            }
        }

        $this->updateControl->addRenderView('applyCard_fail');
    }

    /**
     * 在可申请列表里面的申请卡的操作
     */
    public function onUserApplyCard() {
        
    }

    /**
     * 这个函数用来获取各种可申请的卡列表，包括领取列表，可申请列表
     * @param type $cardType
     * @param type $status
     * @param type $data
     */
    public function getUserMemberCardApplyList($cardType = NULL, $preCardType = NULL, $permitInfo = NULL, $cardInfo = NULL) {

        $applyList = NULL;

        $cardTypeList = array();
        if ($cardType != NULL && $this->getCardType($cardType) != NULL) {
            $cardType = $this->getCardType($cardType);
            $cardTypeList[$cardType->getId()] = $cardType;
        } else {
            $cardTypeList = $this->getCardTypeList('objectList', $preCardType);
        }

        $permitCooker = new BAPermitCooker();
        $userCooker = new BAUserCooker();
        $oUserInfo = $userCooker->getUserInfo();

        $oldApplyList = Blyn::app()->getCurrentUser()->getCache('memberCardApplyList');

        //找出所有的可以申请设置
        foreach ($cardTypeList as $cId => $cardType) {
            $permitList = $permitCooker->getPermitList(array(
                'permit' => self::Permit_Allow_AddCard,
                'cardTypeId' => $cId));
            foreach ($permitList as $id => $permit) {
                $itemData = array();
                $itemData['permitId'] = $id;
                if ($oUserInfo != NULL)
                    $itemData['userInfoId'] = $oUserInfo->getId();

                $card = $this->getCard($itemData, $cardType);
                if ($card == NULL) {//说明用户还没有领取或者领取
                    //如果已经保存过，从保存的数据中取出来
                    if (isset($oldApplyList[$id])) {
                        $oldChangeTime = $oldApplyList[$id];
                        $permitChangeTimeItem = $permit->getItem('lastChangeTime');
                        if ($permitChangeTimeItem) {
                            $permitChangeTime = $permitChangeTimeItem->getValue();
                            if ($permitChangeTime > $oldChangeTime) {
                                $isPermitChanged = TRUE;
                            }
                        }

                        if (!isset($isPermitChanged) || $isPermitChanged == NULL) {
                            $applyList[$id] = $oldApplyList[$id];
                        }
                        continue;
                    }

                    $permitData = array();

                    //$permitData['permit'] = $permit;
                    if ($preCardType != NULL)
                        $permitData['preCardType'] = $preCardType;
                    if ($cardType != NULL) {
                        $cardType = $this->getCardType($cardType);
                        $permitData['cardTypeId'] = $cardType->getId();
                        $preCardType = $this->getPreCardTypeFromCardType($cardType);
                        $permitData['preCardType'] = $preCardType;
                    }
                    if (is_array($permitInfo) && $permitInfo != NULL)
                        $permitData+=$permitInfo;
                    $permitList = $permitCooker->getUserPermitList($permitData);

                    //检查每个许可是否被用户使用过，如果没使用过，就加入申请列表
                    foreach ($permitList as $id => $permit) {
                        if ($oUserInfo != NULL) {
                            $typeId = $permit->getItem('cardTypeId')->getValue();
                            $type = $this->getCardType($typeId);
                            $cardData = array();
                            $cardData['userInfoId'] = $oUserInfo->getId();
                            $cardData['permitId'] = $id;
                            if ($permit->getItem('lastChangeTime'))
                                $applyList[$id] = $permit->getItem('lastChangeTime')->getValue();
                            else {
                                $applyList[$id] = $permit;
                            }
                        } else {//如果还没有用户数据，就直接加入申请列表,并加上最后的更改时间
                            if ($permit->getItem('lastChangeTime'))
                                $applyList[$id] = $permit->getItem('lastChangeTime')->getValue();
                            else {
                                $applyList[$id] = $permit;
                            }
                        }
                    }
                }
            }
        }

        /*

          foreach ($cardTypeList as $id => $cardType) {

          //先获取领取许可表
          $permitData = array();

          //$permitData['permit'] = $permit;
          if ($preCardType != NULL)
          $permitData['preCardType'] = $preCardType;
          if ($cardType != NULL) {
          $cardType = $this->getCardType($cardType);
          $permitData['cardTypeId'] = $cardType->getId();
          $preCardType = $this->getPreCardTypeFromCardType($cardType);
          $permitData['preCardType'] = $preCardType;
          }
          if (is_array($permitInfo) && $permitInfo != NULL)
          $permitData+=$permitInfo;
          $permitList = $permitCooker->getUserPermitList($permitData);

          //检查每个许可是否被用户使用过，如果没使用过，就加入申请列表
          foreach ($permitList as $id => $permit) {
          if ($oUserInfo != NULL) {
          //如果已经有用户信息，检查用户是否有卡
          //如果在这个PERMIT下面还没有卡，
          //就加入申请列表
          $typeId = $permit->getItem('cardTypeId')->getValue();
          $type = $this->getCardType($typeId);
          $cardData = array();
          $cardData['userInfoId'] = $oUserInfo->getId();
          $cardData['permitId'] = $id;
          if (is_array($cardInfo) && $cardInfo != NULL)
          $cardData+=$cardInfo;
          $card = $this->getUserMemberCard($type, $cardData);
          if ($card == NULL) {
          $applyList[$id] = $permit;
          }
          } else {//如果还没有用户数据，就直接加入申请列表
          $applyList[$id] = $permit;
          }
          }
          }
         * 
         */

        if ($applyList != NULL) {
            Blyn::app()->getCurrentUser()->setCache('memberCardApplyList', $applyList);
        }
        return $applyList;
    }

    /**
     * 用于获取用户的各种卡列表，包括正在申请的，已经申请的等等
     * @param type $cardType
     * @param type $status
     * @param type $data
     */
    public function getUserMemberCardList($cardType = NULL, $preCardType = NULL, $status = NULL, $data = NULL) {
        $cardList = array();

        $userCooker = new BAUserCooker();
        $oUserInfo = $userCooker->getUserInfo();

        $itemContext = array();

        if ($oUserInfo != NULL) {
            $itemContext['userInfoId'] = $oUserInfo->getId();

            if ($cardType != NULL) {
                $itemContext['cardTypeId'] = $cardType->getId();
                $memberCardTable = new BASpaceSheet('memberCard', $cardType);
            } else {
                $memberCardTable = new BASpaceSheet('memberCard', BTreeTable::All_Owner);
                if ($preCardType != NULL) {
                    $itemContext['perCardType'] = $preCardType;
                }
            }

            $cardList = $memberCardTable->getView(array('itemData' => $itemContext));
        }
        return $cardList;
    }

    /**
     * this function use to authenticate user mobile and to save user openid     
     */
    public function onAuthUser() {
        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'user_Info');
        $user = Blyn::app()->getCurrentUser();
        foreach ($mediaList as $key => $media) {
            $user->addAttribute('userInfo.' . $key, $media->content);
        }
        $this->updateControl->addRenderView('displayMemberCard', 'memberCard_display');
    }

    /**
     * this function will show apply page for applying memberPoint card 
     * @param type $data
     */
    /*
      public function onShowApplyMemberPointCard($data = NULL) {
      $card = $this->getCurrentMemberCard();
      $this->updateControl->addRenderView('showApplyMemberPointCard', 'memberCard_apply_memberPointCard', array(
      'memberPointCard' => $card
      ));
      }

      public function onShowUserVoucherApplyList() {
      $user = Blyn::app()->getCurrentUser();
      $mobileAttr = $user->getAttribute('userInfo.mobile');
      if ($mobileAttr == NULL || $mobileAttr->getValue() == NULL) {//ask user input mobile
      $this->updateControl->addRenderView('request_user_mobile');
      return;
      }

      $applyList = $this->getUserVoucherApplyList();
      $this->updateControl->addRenderView('userVoucherApplyList', 'user_voucher_apply_list', array(
      'applyList' => $applyList
      ));
      }

      public function onShowUserVoucherList() {
      $user = Blyn::app()->getCurrentUser();
      $mobileAttr = $user->getAttribute('userInfo.mobile');
      if ($mobileAttr != NULL) {
      $mobile = $mobileAttr->getValue();
      $userInfo = array();
      $userInfo['mobile'] = $mobile;
      $cardList = $this->getUserMemberCardList(self::CardType_Voucher_Card, $userInfo);
      if ($cardList == NULL) {
      $cardList = array();
      }
      $this->updateControl->addRenderView('userVoucherList', 'user_voucher_list', array(
      'voucherList' => $cardList
      ));
      return;
      }

      //if not provide mobile, go to apply memberPoint card page
      $this->onShowUserVoucherApplyList();
      }
     * 
     */

    /**
     * some times, member should apply for card, this function
     * will use to handle apply action
     * result of this function should be :
     * 1)directly approve apply
     * 2)send request for processing
     */

    /**
     * this function use to handle request
     * usually should get request type from input
     * the can corresponding function to do some action
     */
    public function onProcessRequest() {
        
    }

    public function onShowRequestList() {
        
    }

    /**
     * some action will send request, then use this function to send request
     * @param type $requestType
     * @param type $message
     * @param type $data
     */
    public function sendRequest($requestType, $message, $data = NULL) {
        
    }

    /**
     * this funtion maybe called onApplyCard, also maybe called when processing 
     * apply request
     */
    public function approveApplyCard() {
        
    }

    /*
      public function applyMemberCard($cardType = null, $cardInfo = NULL, $userInfo = NULL) {

      if (!is_array($userInfo)) {
      $userInfo = array();
      $userInfo['userId'] = Blyn::app()->getCurrentUser()->getId();
      }

      return $this->processApplyMemberCard($cardType, $cardInfo, $userInfo);
      }
     * 
     */

    /**
     * 
     * @param type $cardType
     * @param type $cardInfo
     * @return type
     */
    protected function processApplyMemberCard($cardType, $cardInfo, $userInfo = NULL) {

        $cardType = $this->getCardType($cardType);

        //for voucher
        if (strpos($cardType->getFullName(), self::CardType_Voucher_Card)) {
            $permit = $this->checkApplyCardPermit($cardType, $cardInfo);
            //auto create card
            if ($this->checkApplyCardPermit(self::Permit_Allow_AddCard, $cardType, $userInfo)) {
                $card = $this->addCard($cardType, $cardInfo);
                return array('action' => 'createCard', 'status' => 'completed', 'card' => $card);
            }
            //send approvable message
            if ($this->checkApplyCardPermit(self::Permit_Allow_Approve, $cardType, $userInfo)) {
                $messageTable = new BAMessageSheet('applyCardMessage');
                $message = array();
                $message['applicantId'] = Blyn::app()->getCurrentUser()->getId();
                $message['time'] = time();
                $message['cardTypeId'] = $cardType->getId();
                $message+=$cardInfo;
                if (is_array($userInfo))
                    $message+=$userInfo;
                $oMessage = $messageTable->addList($message);
                return array('action' => 'sendApproveRequest', 'status' => 'completed', 'message' => $oMessage);
            }
        }

        //process for memberPoint card
        if (strpos($cardType->getFullName(), self::CardType_MemberPoint_Card)) {
            //auto create memberPoint account and card if allow add card
            if ($this->checkApplyCardPermit(self::Permit_Allow_AddCard, $cardType, $userInfo)) {
                $memberPointCooker = new BAMemberPointCooker();
                //get memberPoint Type
                $memberPointType = $cardType->getItem('memberPointType')->getValue();
                $memberPointType = $memberPointCooker->getMemberPointType($memberPointType);

                //get memberPointAccount
                $account = $memberPointCooker->getMemberPointAccount($userInfo, $memberPointType);

                if ($account == NULL) {//create it if account not exist
                    $account = $memberPointCooker->addMemberPointAccount($memberPointType, $userInfo);
                }

                if ($account != NULL) {
                    $cardInfo['memberPointAccountId'] = $account->getId();
                }

                $card = $this->addCard($cardType, $cardInfo);
                return array('action' => 'createCard', 'status' => 'completed', 'card' => $card);
            }
            //send approvable message
            if ($this->checkApplyCardPermit(self::Permit_Allow_Approve, $cardType, $userInfo)) {
                $messageTable = new BAMessageSheet('applyCardMessage');
                $message = array();
                $message['applicantId'] = Blyn::app()->getCurrentUser()->getId();
                $message['time'] = time();
                $message['cardTypeId'] = $cardType->getId();
                $message+=$cardInfo;
                if (is_array($userInfo))
                    $message+=$userInfo;
                $oMessage = $messageTable->addList($message);
                return array('action' => 'sendApproveRequest', 'status' => 'completed', 'message' => $oMessage);
            }
        }

        return FALSE;
    }

    protected function checkApplyCardPermit($permit, $cardType, $userInfo = NULL) {
        $permitCooker = new BAPermitCooker();
        $cardType = $this->getCardType($cardType);

        $permitData = array();
        $permitData['cardTypeId'] = $cardType->getId();
        $permitData['permit'] = $permit;

        $userCooker = new BAUserCooker();
        $user = $userCooker->getUserByInfo($userInfo);
        if ($user instanceof BUser) {
            $roles = BRole::findUserRoles($user, NULL, TRUE);
            $roleIdList = array();
            foreach ($roles as $id => $role) {
                $roleIdList[$id] = $id;
            }
            $permitData['roleId'] = $roleIdList;
        }

        return $permitCooker->checkPermit($permitData);
    }

    public function getCurrentMemberCard($data = NULL) {
        $memberCardId = $this->activeLink->getLinkVariable('memberCardId');

        if (is_numeric($memberCardId) && $memberCardId > 0) {
//update value in context variable
            Blyn::app()->getActiveOperation()->addContextVariable('memberCardId', $memberCardId);
        } else {
            if ($memberCardId == NULL) {
                //try to find from context variable
                $memberCardId = Blyn::app()->getActiveOperation()->getContextVariable('memberCardId');
            }
        }

        if (is_numeric($memberCardId) && $memberCardId > 0) {
            $memberCardTable = new BASpaceSheet('memberCard');
            return $memberCardTable->getListById($memberCardId);
        }
        return FALSE;
    }

    public function getCurrentApplyPermit($data = NULL) {
        $applyPermitId = $this->activeLink->getLinkVariable('applyPermitId');

        if (is_numeric($applyPermitId) && $applyPermitId > 0) {
//update value in context variable
            Blyn::app()->getActiveOperation()->addContextVariable('applyPermitId', $applyPermitId);
        } else {
            if ($applyPermitId == NULL) {
                //try to find from context variable
                $applyPermitId = Blyn::app()->getActiveOperation()->getContextVariable('applyPermitId');
            }
        }

        if (is_numeric($applyPermitId) && $applyPermitId > 0) {
            $permitTable = new BASpaceSheet('permit');
            return $permitTable->getListById($applyPermitId);
        }
        return FALSE;
    }

    /*
      public function getUserMemberCardList($preCardType = NULL, $userInfo = NULL) {

      $cardList = array();

      if ($userInfo == NULL) {
      $userInfo = array();
      $userInfo['userId'] = Blyn::app()->getCurrentUser()->getId();
      }

      $userCooker = new BAUserCooker();
      $oUserInfo = $userCooker->getUserInfo($userInfo);

      if ($oUserInfo != NULL) {
      $itemContext = array();
      $itemContext['userInfoId'] = $oUserInfo->getId();
      if ($preCardType != NULL) {
      $itemContext['preCardType'] = $preCardType;
      }

      $memberCardTable = new BASpaceSheet('memberCard');
      $cardList = $memberCardTable->getView(array('itemData' => $itemContext));
      }
      return $cardList;
      }
     * 
     */

    public function getUserMemberCard($cardType = NULL, $userInfo = NULL) {
        $cardList = array();
        $cardType = $this->getCardType($cardType);

        /*
          if ($userInfo == NULL) {
          $userInfo = array();
          $userInfo['userId'] = Blyn::app()->getCurrentUser()->getId();
          }
         * 
         */

        $userCooker = new BAUserCooker();
        $oUserInfo = $userCooker->getUserInfo();

        if ($oUserInfo != NULL) {
            $itemContext = array();
            $itemContext['userInfoId'] = $oUserInfo->getId();
            if ($cardType != NULL) {
                $itemContext['cardTypeId'] = $cardType->getId();
            }

            $memberCardTable = new BASpaceSheet('memberCard', $cardType);
            $card = $memberCardTable->getList(array('itemData' => $itemContext));
            return $card;
        }
        return FALSE;
    }

    public static function getPermitList($format = 'aliasList') {
        return array(
            self::Permit_Allow_AddCard => '直接添加',
            self::Permit_Allow_Approve => '需要审批',
                //self::Permit_Allow_AddCard_For_Birthday => '生日添加'
        );
    }

    public static function getPermitAlias($permit) {
        $permitData = self::getPermitList();

        if (isset($permitData[$permit]))
            return $permitData[$permit];
    }

    /*
      public function getUserVoucherApplyList($permit = self::Permit_Allow_AddCard) {

      $applyList = array();

      $permitCooker = new BAPermitCooker();

      //先获取领取代金券许可表
      $permitData = array();
      $permitData['permit'] = $permit;
      $permitData['preCardType'] = self::CardType_Voucher_Card;
      $permitList = $permitCooker->getUserPermitList($permitData);

      //检查每个许可是否被用户使用过，如果没使用过，就加入申请列表
      foreach ($permitList as $id => $permit) {
      $typeId = $permit->getItem('memberCardTypeId')->getValue();
      $type = $this->getCardType($typeId);
      $card = $this->getUserMemberCard($type, array('userId' => $user->getId(), 'permitId' => $id));
      if ($card == NULL) {
      $applyList[$typeId] = $type;
      }
      }

      return $applyList;
      }
     * 
     */

    public function getApplyPermitList() {

        $permitView = array();

        $cardType = $this->getCurrentCardType();

        if ($cardType != NULL) {
            $permitData = array();
            $permitData['cardTypeId'] = $cardType->getId();

            $permitCooker = new BAPermitCooker();
            $permitView = $permitCooker->getPermitList($permitData);
        }

        return $permitView;
    }

    public function onShowAddApplyPermit() {

        $theModel = new BDynamicFormModel();

        $permitField = 'media_permit_addCard_permit';
        $roleIdField = 'media_roleId_addCard_permit';
        $expireTimeField = 'media_expireTime_addCard_permit';

        $theModel->addField($permitField);
        $theModel->addField($roleIdField);
        $theModel->addField($expireTimeField);

        $permitCooker = new BAPermitCooker();
        $permit = $permitCooker->getCurrentPermit();
        if ($permit != NULL) {
            if ($permit->getItem('permit') != NULL) {
                $theModel->$permitField = $permit->getItem('permit')->getValue();
            }
            if ($permit->getItem('roleId') != NULL) {
                $theModel->$roleIdField = $permit->getItem('roleId')->getValue();
            }
            if ($permit->getItem('expireTime') != NULL) {
                $theModel->$expireTimeField = $permit->getItem('expireTime')->getValue();
            }
        }

        $this->updateControl->addRenderView('applyPermitAdd', 'memberCardType_applyPermit_add', array(
            'model' => $theModel,
            'permitField' => $permitField,
            'roleIdField' => $roleIdField,
            'expireTimeField' => $expireTimeField
        ));
    }

    public function showApplyPermitList($control = NULL) {
        $renderControl = $this->updateControl;
        if ($control != NULL) {
            $renderControl = $control;
        }

        $renderControl->addRenderView('applyPermitList', 'memberCardType_applyPermit_list', array(
            'permitView' => $this->getApplyPermitList(),
        ));
        $renderControl->render();
    }

    public function onAddApplyPermit() {

        $mediaList = $this->postManager->populateMediaListFromPostData($this->postData, 'addCard_permit');

        $permitData = array();
        foreach ($mediaList as $media) {
            if ($media->content != NULL)
                $permitData[$media->name] = $media->content;
        }

        $this->addCardTypePermit($permitData);

        /*
          $cardType = $this->getCurrentCardType();
          $permitData['cardTypeId'] = $cardType->getId();

          $permitCooker = new BAPermitCooker();

          $permitCooker->addPermit($permitData);
         * 
         */

        $this->onShowApplyPermitList();
    }

    public function onShowApplyPermitList() {
        $permitView = $this->getApplyPermitList();
        $this->updateControl->addRenderView('permitList', 'memberCardType_applyPermit_list', array(
            'permitView' => $permitView
        ));
    }

    public function addCardTypePermit($permitData, $cardType = NULL) {
        if ($cardType == NULL) {
            $cardType = $this->getCurrentCardType();
        }
        if ($cardType != NULL) {
            $preCardType = $this->getPreCardTypeFromCardType($cardType);
            if (!is_array($permitData)) {
                $permitData = array();
            }
            $permitData['cardTypeId'] = $cardType->getId();
            if ($preCardType != NULL) {
                $permitData['preCardType'] = $preCardType;
            }

            $permitCooker = new BAPermitCooker();
            $permit = $permitCooker->getPermit($permitData);
            if ($permit == NULL) {
                $permit = $permitCooker->addPermit($permitData);
            }
            return $permit;
        }
        return FALSE;
    }

}
